package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lljjcoder.Interface.OnCustomCityPickerItemClickListener;
import com.lljjcoder.bean.CustomCityData;
import com.lljjcoder.citywheel.CustomConfig;
import com.lljjcoder.style.citycustome.CustomCityPicker;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AddrListBean;
import com.shenzhen.horselive.beans.AddressBean;
import com.shenzhen.horselive.beans.ApplyCardBean;
import com.shenzhen.horselive.beans.CityAmountBean;
import com.shenzhen.horselive.beans.CityListBean;
import com.shenzhen.horselive.beans.CodeBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.MessageEventWXPayresult;
import com.shenzhen.horselive.beans.OpenCardCityDateBean;
import com.shenzhen.horselive.beans.OpenCardResultBean;
import com.shenzhen.horselive.beans.PayResultBean;
import com.shenzhen.horselive.common.utils.handler.IFilterHandler;
import com.shenzhen.horselive.databinding.ActivityApplyOpenCardBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.ui.dialog.DialogPayways;
import com.shenzhen.horselive.utils.AliPayUtils;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.utils.GetJsonDataUtil;
import com.shenzhen.horselive.utils.PayResult;
import com.shenzhen.horselive.widget.AreaPicker;
import com.shenzhen.horselive.wx.WXManager;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.tools.json.JsonUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ApplyOpenCardActivity extends AppBarActivity {

    ActivityApplyOpenCardBinding  binding;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        checkPayResult();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。 showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        showToast("支付取消");

                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventWXPayresult event) {
        //微信支付的回调
        if (event.getCode()==0)
        {
            checkPayResult();
        }else
        {
            showToast("支付取消");
        }

    };



    private String  orderrCode;
    private  String  channelTag;
    //查询支付结果
    private void checkPayResult() {
        if (orderrCode==null||channelTag==null)
        {
            return;
        }
        //支付成功
        ApiFactory.getApiService().getPayResult(User.get().getMyInfo().getToken()
                ,orderrCode,channelTag
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayResultBean>(this) {
                    @Override
                    protected void onNextInActive(PayResultBean payResultBean) {
                        if (payResultBean.isSuccess()&&payResultBean.getData().getPayStatus()==1)
                        {
                            showToast("申请成功");
                            finish();
                        }
                        else {
                            showToast(payResultBean.getErrMessage());
                        }
                    }
                });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityApplyOpenCardBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //先定位
        setStyleDark();
        setTitle("申请预约");
        initViews();
        location();
        intitData();
    }

    TencentLocationManager  locationManager;
    private  void  location()
    {
        locationManager = TencentLocationManager.getInstance(this);
        //单点定位
        String[] permissions = {
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION,
                Permission.READ_PHONE_STATE,
                Permission.WRITE_EXTERNAL_STORAGE,
        };

        XXPermissions.with(this)
                .permission(permissions)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all)
                        {

                            TencentLocationRequest request = TencentLocationRequest.create();
                            request.setRequestLevel(3)//包含区域信息
                                    .setAllowGPS(true)
                                    .setIndoorLocationMode(true)
                                    .setInterval(5000)
                            ;
                            int error = locationManager.requestLocationUpdates(request, locationListener, Looper.getMainLooper());
                            if (error == 0)
                                Log.e("addr","注册位置监听器成功！");
                            else
                                Log.e("addr","注册位置监听器失败！");
//                    locationManager.requestSingleFreshLocation(null, locationListener, Looper.getMainLooper());
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });



    }


    private String  areaCode ="";
    private String  cityId ="";
    private TencentLocationListener locationListener = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
            //获取到定位信息
            locationManager.removeUpdates(locationListener);
            if(i == TencentLocation.ERROR_OK){
                //定位成功
              CodeBean  codeBean =  GetJsonDataUtil.getInstance().getCode(tencentLocation.getProvince(),tencentLocation.getCity(),tencentLocation.getDistrict());
              if (codeBean!=null)
              {
              cityId = codeBean.getCityCode();
              areaCode =  codeBean.getDistrictCode();
              }
            }
            else
            {
                Log.v("map",i+s);
            }

        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    };



    private void intitData() {
        //查看有没有默认的地址有就填上
        ApiFactory.getApiService().getAddressList(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AddrListBean>(this) {
                    @Override
                    protected void onNextInActive(AddrListBean addrListBean) {
                        if (addrListBean.isSuccess())
                        {
                            if (addrListBean.getData()!=null)
                            {
                                for (int i = 0; i < addrListBean.getData().size(); i++) {
                                    AddressBean  bean = addrListBean.getData().get(i);
                                    if ("1".equals(bean.getDef()))
                                    {
                                        myaddrbean = bean;
                                        binding.imgAddAddr.setVisibility(View.GONE);
                                        binding.containerAddr.setVisibility(View.VISIBLE);
                                        binding.tvAddrName.setText(myaddrbean.getProvince()+myaddrbean.getCity()+myaddrbean.getCounty());
                                        binding.tvAddrDetails.setText(myaddrbean.getAddress());
                                        //设置地址
                                        break;
                                    }
                                }
                            }
                        }
                    }
                });


        //获取城市
      ApiFactory.getApiService().openCardcityAreaList(User.get().getMyInfo().getToken())
              .compose(SchedulersCompat.applyIoSchedulers())
              .safeSubscribe(new LoadingViewObserver<OpenCardCityDateBean>(this) {
                  @Override
                  protected void onNextInActive(OpenCardCityDateBean cityListBean) {
                      if (cityListBean.isSuccess())
                      {

                          //省列表
                          provenceList =cityListBean.getData();
                          //造数据
                          List<CustomCityData> customProvenceDataList = new ArrayList<>();
                          for (OpenCardCityDateBean.DataBean  dataBean:provenceList
                          ) {
                              //省份
                              CustomCityData  customProvenceData = new CustomCityData();
                              customProvenceData.setId(dataBean.getCode());
                              customProvenceData.setName(dataBean.getName());

                              //城市
                              List<CustomCityData>  cityDataList=  new ArrayList<>();
                              for (OpenCardCityDateBean.DataBean.AreaListBeanX city:dataBean.getAreaList()
                              ) {
                                  CustomCityData  cityData =  new CustomCityData();
                                  cityData.setId(city.getCode());
                                  cityData.setName(city.getName());

//                                  城市的区
                                  List<CustomCityData>  areaList =new ArrayList<>();
                                  for (OpenCardCityDateBean.DataBean.AreaListBeanX.AreaListBean areaBean:city.getAreaList()
                                  ) {
                                      CustomCityData  areaData =  new CustomCityData();
                                      areaData.setName(areaBean.getName());
                                      areaData.setId(areaBean.getCode());
                                      areaList.add(areaData);
                                  }
                                  cityData.setList(areaList);
                                  cityDataList.add(cityData);
                              }
                              customProvenceData.setList(cityDataList);
                              customProvenceDataList.add(customProvenceData);
                          }

                          //配置设置
                          CustomConfig cityConfig = new CustomConfig.Builder()
                                  .title("选择城市")
                                  .visibleItemsCount(5)
                                  .setCityData(customProvenceDataList)//设置数据源
                                  .provinceCyclic(false)
                                  .cityCyclic(false)
                                  .districtCyclic(false)
//                                  .setCityWheelType(CustomConfig.WheelType.PRO_CITY)//只显示城市
                                  .build();

                          customCityPicker = new CustomCityPicker(getContext());
                          customCityPicker.setCustomConfig(cityConfig);
                          customCityPicker.setOnCustomCityPickerItemClickListener(new OnCustomCityPickerItemClickListener() {
                              @Override
                              public void onSelected(CustomCityData province, CustomCityData city, CustomCityData district) {
                                  if (province != null && city != null) {
                                      //先显示出来
                                      binding.tvChooseCity.setText(province.getName()+city.getName()+district.getName());

                                      myprovince = province.getName();
                                      mycity  =city.getName();
                                      myDisrect = district.getName();
                                      openAreaCode =district.getId();
                                     //查看状态
                                      checkCityState(province.getId(),city.getId(),district.getId());
                                  }else{
                                      showToast("结果出错！");
                                  }
                              }
                          });

                      }
                      else
                      {
                          showToast(cityListBean.getErrMessage());
                      }
                  }
              });


    }
    //选中的areacode;
    private   String  openAreaCode;

    //查看城市是否需要支付保证金
    int  state =1;
    private void checkCityState(String proId, String cityId, String id) {
        if (cityId==null||proId==null)
            return;
        if (provenceList==null)
            return;
        for (OpenCardCityDateBean.DataBean dataBean:provenceList) {

            if (proId.equals(dataBean.getCode()))
            {

                for (OpenCardCityDateBean.DataBean.AreaListBeanX  citybean:dataBean.getAreaList()
                ) {
                     if (cityId.equals(citybean.getCode()))
                     {

                         //区域循环
                         for (OpenCardCityDateBean.DataBean.AreaListBeanX.AreaListBean areaBean:citybean.getAreaList()
                              ) {

                             if (id.equals(areaBean.getCode()))
                             {
                                 //这里做处理
                                 //设置备注
                                 if (areaBean.getStatus()!=null)
                                 state = Integer.parseInt(areaBean.getStatus());
                                 if (state==1)
                                 {
                                     //城市可用
                                     binding.tvNotice.setVisibility(View.INVISIBLE);
                                     binding.containerNoPermiss.setVisibility(View.GONE);
                                 }
                                 else if (state==0)
                                 {
                                     binding.tvNotice.setVisibility(View.VISIBLE);
                                     binding.tvNotice.setText(String.format("备注：该城市权限尚未开通，您需先缴纳预约金%s元",this.dataBean.getBondAmount()));
                                     binding.containerNoPermiss.setVisibility(View.VISIBLE);
                                     binding.tvMoney.setText("¥"+this.dataBean.getBondAmount());
                                     binding.tvNotice1.setText(String.format("城市权限开通且开卡成功后，平台将退还您的预约金至您的蜂值账户，邀请团队成员缴纳预约金开卡成功%s天以后，您可获得相应比例的蜂值奖励",this.dataBean.getCanCancelDays()));
                                 }
                                 break;

                             }


                         }


                         break;
                     }
                }
                break;

            }



        }


    }


    private CustomCityPicker  customCityPicker;

    List<OpenCardCityDateBean.DataBean>  provenceList;

    ApplyCardBean.DataBean  dataBean;
    //初始化视图
    private void initViews() {
        dataBean = (ApplyCardBean.DataBean) getIntent().getSerializableExtra("data");
        binding.tvType.setText(dataBean.getSchemeTitle());
        //城市选择
        binding.tvChooseCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCityPick();
            }
        });
        //地址选择
        binding.containerAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseAddr();
            }
        });

        binding.imgAddAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseAddr();
            }
        });


        //提交申请信息
        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });




    }

    //选择地址
    private void chooseAddr() {
        Intent  intent  = new Intent(this,AddrListActivity.class);
        intent.putExtra("iscall",true);
        startActivityForResult(intent,1000);
    }

    //提交注册信息
    private void submit() {
        if (myprovince==null||mycity==null||myDisrect==null)
        {
            showToast("请填写申请省份和城市和区");
            return;
        }

        String  name = binding.etName.getText().toString();
        if (TextUtils.isEmpty(name))
        {
            showToast("请填写申请姓名");
            return;
        }

        String  phone =  binding.etPhone.getText().toString();
        if (TextUtils.isEmpty(phone))
        {
            showToast("请填写手机号码");
            return;
        }
        if (myaddrbean==null)
        {
            showToast("请填写收货地址");
            return;
        }

        if (state==1)
        {
            ApiFactory.getApiService().applyOpenCard(User.get().getMyInfo().getToken()
                    ,dataBean.getBrandId(),User.get().getMyInfo().getId()+"",phone,
                    name,myprovince,mycity,myDisrect,openAreaCode,dataBean.getId()+"",dataBean.getSchemeTitle()
                    ,myaddrbean.getContactsName(),myaddrbean.getContactsPhone(),myaddrbean.getProvince()+myaddrbean.getCity()+myaddrbean.getCounty()
                    ,myaddrbean.getAddress(),areaCode,cityId
            ).compose(SchedulersCompat.applyIoSchedulers())
                    .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                        @Override
                        protected void onNextInActive(CommResponseBean commResponseBean) {
                            if (commResponseBean.isSuccess())
                            {
                                showToast("申请成功");
                                finish();
                            }
                        }
                    });
        }
        else if (state==0)
        {
            //需要付钱
            DialogManager.getInstance().showPayWaysDialog(getContext(),this.dataBean.getBondAmount(), new DialogPayways.OnButtonClick() {
                @Override
                public void onClick(int type) {
                    if (type==0)
                    {
                        //微信支付
                        ApiFactory.getApiService().applyOpenCardWithPay(User.get().getMyInfo().getToken()
                                ,dataBean.getBrandId(),User.get().getMyInfo().getId()+"",phone,
                                name,myprovince,mycity,myDisrect,openAreaCode,dataBean.getId()+"",dataBean.getSchemeTitle()
                                ,myaddrbean.getContactsName(),myaddrbean.getContactsPhone(),myaddrbean.getProvince()+myaddrbean.getCity()+myaddrbean.getCounty()
                                ,myaddrbean.getAddress(),areaCode,cityId,"SPSDKWX_PAY"
                        ).compose(SchedulersCompat.applyIoSchedulers())
                                .safeSubscribe(new LoadingViewObserver<OpenCardResultBean>(ApplyOpenCardActivity.this) {
                                    @Override
                                    protected void onNextInActive(OpenCardResultBean commResponseBean) {
                                        if (commResponseBean.isSuccess())
                                        {
//                                            showToast("申请成功");
//                                            finish();
                                            channelTag ="SPSDKWX_PAY";
                                            orderrCode =commResponseBean.getData().getOrderCode();
                                            WXManager.getInstance().goToPay(commResponseBean.getData().getPayResult());
                                        }
                                    }
                                });




                    }else if (type==1)
                    {
                        //支付宝支付SPSDKALI_PAY
                        ApiFactory.getApiService().applyOpenCardWithPay(User.get().getMyInfo().getToken()
                                ,dataBean.getBrandId(),User.get().getMyInfo().getId()+"",phone,
                                name,myprovince,mycity,myDisrect,openAreaCode,dataBean.getId()+"",dataBean.getSchemeTitle()
                                ,myaddrbean.getContactsName(),myaddrbean.getContactsPhone(),myaddrbean.getProvince()+myaddrbean.getCity()+myaddrbean.getCounty()
                                ,myaddrbean.getAddress(),areaCode,cityId,"SPSDKALI_PAY"
                        ).compose(SchedulersCompat.applyIoSchedulers())
                                .safeSubscribe(new LoadingViewObserver<OpenCardResultBean>(ApplyOpenCardActivity.this) {
                                    @Override
                                    protected void onNextInActive(OpenCardResultBean commResponseBean) {
                                        if (commResponseBean.isSuccess())
                                        {
                                            channelTag ="SPSDKALI_PAY";
                                            orderrCode =commResponseBean.getData().getOrderCode();
//                                            showToast("申请成功");
//                                            finish();
                                            //支付宝支付
                                            Runnable payRunnable = new Runnable() {
                                                @Override
                                                public void run() {
                                                    PayTask alipay = new PayTask(ApplyOpenCardActivity.this);
                                                    Map<String,String> result = alipay.payV2(commResponseBean.getData().getPayResult(),true);
                                                    Message msg = new Message();
                                                    msg.what = SDK_PAY_FLAG;
                                                    msg.obj = result;
                                                    handler.sendMessage(msg);
                                                }
                                            };
                                            // 必须异步调用
                                            Thread payThread = new Thread(payRunnable);
                                            payThread.start();
                                        }
                                    }
                                });

                    }
                }
            });

        }


    }

    String  myprovince ;
    String   mycity ;
    String  myDisrect;
    //打开城市选择器
    private void openCityPick() {
//        AreaPicker areaPicker = new AreaPicker();
//        areaPicker.setListener(new AreaPicker.AreaPickerListener() {
//            @Override
//            public void onPicked(String province, String city) {
//                myprovince  =province;
//                mycity  =city;
//                binding.tvChooseCity.setText(province+""+city);
//            }
//        });
//        areaPicker.show(getSupportFragmentManager());

        if (customCityPicker!=null)
        {
            customCityPicker.showCityPicker();
        }

    }


       public static void start(Context context, ApplyCardBean.DataBean  dataBean) {
        Intent starter = new Intent(context, ApplyOpenCardActivity.class);
        starter.putExtra("data",dataBean);
        context.startActivity(starter);
    }


    AddressBean  myaddrbean;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000&&resultCode==1001)
        {
            if (data!=null)
            {
                if (data.getSerializableExtra("data")!=null)
                {
                  myaddrbean = (AddressBean) data.getSerializableExtra("data");
                  binding.imgAddAddr.setVisibility(View.GONE);
                  binding.containerAddr.setVisibility(View.VISIBLE);
                  binding.tvAddrName.setText(myaddrbean.getProvince()+myaddrbean.getCity()+myaddrbean.getCounty());
                  binding.tvAddrDetails.setText(myaddrbean.getAddress());
                }
            }
        }
    }
}